﻿using MinorAspNetCore.Server;
using System;
using System.Collections.Specialized;
using System.IO;
using System.Text;
using System.Threading.Tasks;

namespace MinorAspNetCore
{
    public class MinorHttpContext
    {
        public MinorHttpRequest Request { get; }

        public MinorHttpResponse Response { get; }

        public MinorHttpContext(IMinorFeatureCollection features)
        {
            Request = new MinorHttpRequest(features);
            Response = new MinorHttpResponse(features);
        }
    }

    public class MinorHttpRequest
    {
        private readonly IMinorHttpRequestFeature _feature;

        public Uri Url => _feature.Url;

        public NameValueCollection Headers => _feature.Headers;

        public Stream Body => _feature.Body;

        public MinorHttpRequest(IMinorFeatureCollection features) => _feature = features.Get<IMinorHttpRequestFeature>();
    }

    public class MinorHttpResponse
    {
        private readonly IMinorHttpResponseFeature _feature;

        public MinorHttpResponse(IMinorFeatureCollection features) => _feature = features.Get<IMinorHttpResponseFeature>();

        public NameValueCollection Headers => _feature.Headers;

        public Stream Body => _feature.Body;

        public int StatusCode { get => _feature.StatusCode; set => _feature.StatusCode = value; }
    }

    public static partial class Extensions
    {
        public static Task WriteAsync(this MinorHttpResponse response, string contents)
        {
            byte[] buffer = Encoding.UTF8.GetBytes(contents);
            return response.Body.WriteAsync(buffer, 0, buffer.Length);
        }
    }
}